package com.zou.jokes.adapter;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.binaryresource.FileBinaryResource;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.common.file.FileUtils;
import com.facebook.common.util.UriUtil;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.ProgressBarDrawable;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.zou.jokes.Constant;
import com.zou.jokes.HiddenActivity;
import com.zou.jokes.R;
import com.zou.jokes.beans.BaseDataEntity;
import com.zou.jokes.sqlite.MyDao;
import com.zou.jokes.utils.FileUtil;
import com.zou.jokes.utils.RxBus;
import com.zou.jokes.utils.ToastUtil;
import com.zou.jokes.utils.UserEvent;

import java.io.File;
import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by zou on 2016/6/3.
 */
public class PicsAdapter extends RecyclerView.Adapter implements View.OnClickListener {

    private static final int     TIME          = 0;
    private static final int     MORE          = 1;
    private static final int     PICS          = 2;
    private              boolean isLoadingMore = false;
    private final List<BaseDataEntity> datas;
    ClipboardManager clipboardManager;
    Context          context;
    private final MyDao                         myDao;
    private final GenericDraweeHierarchyBuilder builder;

    public void setLoadingMore(boolean loadingMore) {
        isLoadingMore = loadingMore;
    }

    public PicsAdapter(List<BaseDataEntity> datas, Context context) {
        this.datas = datas;
        this.context = context;
        this.clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        myDao = new MyDao(context);

        builder = new GenericDraweeHierarchyBuilder(context.getResources());

    }

    @Override

    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TIME:
                return new TimeHodler(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_time, parent, false));
            case MORE:
                return new MoreHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_more, parent, false));
            case PICS:
                return new PicsHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_pics, parent, false));
            default:
                return null;

        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof PicsHolder) {
            ((PicsHolder) holder).btn_copy_content.setTag(position);
            ((PicsHolder) holder).btn_copy_content.setOnClickListener(this);
            ((PicsHolder) holder).btn_share_joke.setTag(position);
            ((PicsHolder) holder).btn_share_joke.setOnClickListener(this);
            ((PicsHolder) holder).btn_share_joke.setClickable(false);
            ((PicsHolder) holder).btn_like_joke.setTag(position);
            ((PicsHolder) holder).btn_like_joke.setOnClickListener(this);


            ((PicsHolder) holder).joke_content.setText(datas.get(position - 1).getContent());
            ((PicsHolder) holder).update_time.setText(datas.get(position - 1).getUpdatetime());

/*
            ViewTreeObserver vto = ((PicsHolder) holder).draweeView.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(() -> width = ((PicsHolder) holder).draweeView.getWidth());
*/
            ((PicsHolder) holder).draweeView.setAspectRatio(3f);

            GenericDraweeHierarchy hierarchy = builder.setFadeDuration(300)
                    .setProgressBarImage(new ProgressBarDrawable())
                    .setPlaceholderImage(context.getResources().getDrawable(R.drawable.ic_insert_emoticon_yellow_24dp))
                    .setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY)
                    .build();
            ((PicsHolder) holder).draweeView.setHierarchy(hierarchy);
            Log.e("wocao", "onBindViewHolder: " + datas.get(position - 1).getUrl());
//            ((PicsHolder) holder).draweeView.setImageURI(Uri.parse(datas.get(position - 1).getUrl()));\

//            fresco图片加载监听
            ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
                @Override
                public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                    if (imageInfo == null) {
                        return;
                    }
                    int x = imageInfo.getWidth();
                    int y = imageInfo.getHeight();
                    Log.e("wocao", "onFinalImageSet: " + "x=" + x + " y=" + y);
                    ((PicsHolder) holder).draweeView.setAspectRatio((float) x / y);
                    Log.e("wocao", ((PicsHolder) holder).draweeView.getAspectRatio() + "ratio");

//                    下载完后可点击
                    ((PicsHolder) holder).btn_share_joke.setClickable(true);

                }
            };


            DraweeController controller = Fresco.newDraweeControllerBuilder().setAutoPlayAnimations(true)
                    .setUri(Uri.parse(datas.get(position - 1).getUrl()))
                    .setControllerListener(controllerListener)
                    .build();
            ((PicsHolder) holder).draweeView.setController(controller);

/*            if (myDao.queryExists(datas.get(position - 1).getHashId())) {
                ((PicsHolder) holder).btn_like_joke.setImageResource(R.drawable.ic_favorite_black_24dp);
            }*/


            Observable.just(myDao.queryExists(datas.get(position - 1).getHashId()))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            ((PicsHolder) holder).btn_like_joke.setImageResource(R.drawable.ic_favorite_black_24dp);
                        } else {
                            ((PicsHolder) holder).btn_like_joke.setImageResource(R.drawable.ic_favorite_border_black_24dp);
                        }
                    });
        }
    }

    @Override
    public int getItemCount() {
//        不足20条不会显示加载更多,没有条目不会显示更新时间
//        屏蔽掉gif后。。
        if (datas.size() == 0) {
            return 0;
//        } else if (datas.size() < 20) {
//            return datas.size() + 1;
        } else {
            return datas.size() + 2;
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TIME;
        } else if (position == datas.size() + 1) {
            return MORE;
        } else {
            return PICS;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_copy_content:
                clipboardManager.setPrimaryClip(ClipData.newPlainText("joke", datas.get((Integer) v.getTag() - 1).getUrl()));
                ToastUtil.showToast(context, "已复制图片链接");
                Log.e("wocao", "onClick: " + clipboardManager.getPrimaryClip());
                break;
            case R.id.btn_share_joke:

                //                获取缓存图片
                String url = datas.get((Integer) v.getTag()).getUrl();
                String[] split = url.split("/");
                String fileName = split[split.length - 1];
                FileBinaryResource resource = (FileBinaryResource) Fresco.getImagePipelineFactory()
                        .getMainFileCache().getResource(new SimpleCacheKey(datas.get((Integer) v.getTag() - 1).getUrl()));
                File file = resource.getFile();
                Log.e("wocao", "fresco cache: " + file.getAbsolutePath());
                Log.e("wocao", "filename: " + fileName);

                File localFile = new File(context.getExternalFilesDir(null), fileName);

                FileUtil.copyfile(file, localFile);

                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_SUBJECT, "分享趣图");
                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(localFile));
                context.startActivity(Intent.createChooser(intent, "分享趣图"));


                break;
            case R.id.btn_like_joke:
                Observable.just(myDao.queryExists(datas.get((Integer) v.getTag() - 1).getHashId()))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aBoolean -> {
                            if (!aBoolean) {
                                Observable.just(myDao.addDate(System.currentTimeMillis()
                                        , datas.get((Integer) v.getTag() - 1).getContent()
                                        , datas.get((Integer) v.getTag() - 1).getHashId()
                                        , datas.get((Integer) v.getTag() - 1).getUnixtime()
                                        , datas.get((Integer) v.getTag() - 1).getUpdatetime()
                                        , datas.get((Integer) v.getTag() - 1).getUrl()
                                ))
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(aLong -> {
                                            if (aLong != -1) {
                                                ((ImageView) v).setImageResource(R.drawable.ic_favorite_black_24dp);
                                                ToastUtil.showToast(context, "已收藏");
                                                RxBus.getDefault().post(new UserEvent(Constant.UPDATEFAV, ""));
                                            }
                                        });
                            } else {
                                Observable.just(myDao.deleteDate(datas.get((Integer) v.getTag() - 1).getHashId()
                                ))
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(integer -> {

                                            if (integer == 1) {
                                                ((ImageView) v).setImageResource(R.drawable.ic_favorite_border_black_24dp);
                                                ToastUtil.showToast(context, "已取消收藏");
                                                RxBus.getDefault().post(new UserEvent(Constant.UPDATEFAV, ""));
                                            }

                                        });
                            }
                        });

        }
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        if (holder instanceof MoreHolder) {
            if (!isLoadingMore) {
                Log.e("wocao", "onViewAttachedToWindow: send event");
                RxBus.getDefault().post(new UserEvent(Constant.PICSLOADMORE, ""));
                isLoadingMore = true;
            }
        }

    }

    class PicsHolder extends RecyclerView.ViewHolder {
        TextView         joke_content;
        TextView         update_time;
        ImageButton      btn_copy_content;
        ImageButton      btn_share_joke;
        ImageButton      btn_like_joke;
        SimpleDraweeView draweeView;


        public PicsHolder(View itemView) {
            super(itemView);
            joke_content = (TextView) itemView.findViewById(R.id.joke_content);
            update_time = (TextView) itemView.findViewById(R.id.update_time);
            btn_copy_content = (ImageButton) itemView.findViewById(R.id.btn_copy_content);
            btn_share_joke = (ImageButton) itemView.findViewById(R.id.btn_share_joke);
            btn_like_joke = (ImageButton) itemView.findViewById(R.id.btn_like_joke);
            draweeView = (SimpleDraweeView) itemView.findViewById(R.id.drawee);
        }
    }


    //    加载更多
    class MoreHolder extends RecyclerView.ViewHolder {
        public MoreHolder(View itemView) {
            super(itemView);
        }
    }

    //    提示加载时间
    class TimeHodler extends RecyclerView.ViewHolder {
        public TimeHodler(View itemView) {
            super(itemView);
            itemView.setOnClickListener(v -> context.startActivity(new Intent(context, HiddenActivity.class)));
        }
    }
}
